<?php

namespace app\controllers;

use app\librarys\aliyun_sms\AliSms;
use app\librarys\getui\GetuiClient;
use app\librarys\Tools;
use app\models\Menu;
use app\models\Merchant;
use app\models\SaleArticle;
use app\models\Sms;
use Yii;
use yii\web\Controller;
use app\models\LoginForm;
use app\models\ContactForm;

class SiteController extends Controller
{
    public $layout = false;
    public $enableCsrfValidation = false;

//    /**
//     * @inheritdoc
//     */
//    public function behaviors()
//    {
//        return [
//            'access' => [
//                'class' => AccessControl::className(),
//                'only' => ['logout'],
//                'rules' => [
//                    [
//                        'actions' => ['logout'],
//                        'allow' => true,
//                        'roles' => ['@'],
//                    ],
//                ],
//            ],
//            'verbs' => [
//                'class' => VerbFilter::className(),
//                'actions' => [
//                    'logout' => ['post'],
//                ],
//            ],
//        ];
//    }
//
//    /**
//     * @inheritdoc
//     */
//    public function actions()
//    {
//        return [
//            'error' => [
//                'class' => 'yii\web\ErrorAction',
//            ],
//            'captcha' => [
//                'class' => 'yii\captcha\CaptchaAction',
//                'fixedVerifyCode' => YII_ENV_TEST ? 'testme' : null,
//            ],
//        ];
//    }

    /**
     * Displays homepage.
     *
     * @return string
     */
    public function actionIndex()
    {
        return $this->redirect('site/login');
//        return $this->render('index');
    }

    /**
     * Login action.
     *
     * @return string
     */
    public function actionLogin()
    {
        $model = new LoginForm();
        $redirectUrl = \Yii::$app->request->get('redirect_url');
        if ($model->load(\Yii::$app->request->post()) && $model->login()) {
            if (empty($redirectUrl)) {
                $indexPhp = \Yii::$app->urlManager->showScriptName ? '/index.php' : '';

                // 找出当前登录管理员权限所能访问的第一个页面
                $url = '/dashboard/index';
                $menus = Menu::getAllMenus();
                foreach ($menus as $menu) {
                    if (isset($menu['sub_menu_list'])) {
                        if (count($menu['sub_menu_list']) > 0) {
                            $url = '/' . $menu['sub_menu_list'][0]['controller'] . '/' . $menu['sub_menu_list'][0]['action'];
                        }
                    } else {
                        $url = '/' . $menu['controller'] . '/' . $menu['action'];
                    }
                    break;
                }

                $redirectUrl = \Yii::$app->request->baseUrl . $indexPhp . $url;
            }
            return $this->redirect($redirectUrl);
        }
        return $this->render('login', [
            'model' => $model,
            'redirect_url' => $redirectUrl
        ]);
    }

    /**
     * Logout action.
     *
     * @return string
     */
    public function actionLogout()
    {
        Yii::$app->session->removeAll();
        return $this->redirect(Tools::urlBase() . "/site/login");
    }

    /**
     * Displays contact page.
     *
     * @return string
     */
    public function actionContact()
    {
        $model = new ContactForm();
        if ($model->load(Yii::$app->request->post()) && $model->contact(Yii::$app->params['adminEmail'])) {
            Yii::$app->session->setFlash('contactFormSubmitted');

            return $this->refresh();
        }
        return $this->render('contact', [
            'model' => $model,
        ]);
    }

    /**
     * Displays about page.
     *
     * @return string
     */
    public function actionAbout()
    {
        return $this->render('about');
    }


    public function actionAd()
    {
        return $this->render('ad');
    }

    /**
     * @return string
     */
    public function actionSale()
    {
        return $this->render('sale');
    }

    public function actionSmsTest()
    {
//        $sms_sign_name = \Yii::$app->params['aliyun.message.service.SMSSignName'];
//        $sms = new AliSms();
//        $user_phones = ['18375893163','13370704388'];
//        $sms_template_code = 'SMS_89395035';
//                $sms_params = [
//            'code' => 'yes i do'
//        ];
//        foreach ($user_phones as $user_phone) {
//            $result = $sms->sendSms($sms_sign_name, $sms_template_code, $user_phone, $sms_params);
//            var_dump($result);
//
////            结果示例 ok
////            array (size=4)
//            //  'Message' => string 'OK' (length=2)
//            //  'RequestId' => string 'AED33451-CEE2-410D-A090-97CCCD411056' (length=36)
//            //  'BizId' => string '602910903763279095^0' (length=20)
//            //  'Code' => string 'OK' (length=2)
////            结果示例 fail
////            array (size=3)
//            //  'Message' => string '触发分钟级流控Permits:1' (length=30)
//            //  'RequestId' => string '942AAC1D-091D-4B0B-A59C-BD5D39567F5C' (length=36)
//            //  'Code' => string 'isv.BUSINESS_LIMIT_CONTROL' (length=26)
//        }
        Sms::sendSms('13637993158', ['123', 5], 201187);
        exit;
    }

    public function actionTestPush()
    {
        GetuiClient::pushMessageToSingle('ac031077ff6f23c98aa4af1e02e9dc2d', '这是测试推送内容');
    }

    public function actionSaleArticleShow()
    {
        $id = \Yii::$app->request->get('id');
        $item = SaleArticle::getById($id);
        return $this->render('sale-article-show', ['item' => $item]);
    }

    public function actionTestMerchantPush()
    {
        $ad_id = '00a13e57-a581-11e7-84d9-00163e06b8e1';
        Merchant::setGiftPaySuccess($ad_id);
    }


    public function actionTestYingye()
    {
//        $url = 'http://frings-test.oss-cn-shanghai.aliyuncs.com/test/1.jpg';
//        $ch = curl_init();
//        curl_setopt($ch, CURLOPT_URL, $url);
//        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
//        curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
//        $file = curl_exec($ch);
//        curl_close($ch);
//        $filename = pathinfo($url, PATHINFO_BASENAME);
//        $path = '../web/download/'.date('YmdHis').$filename;
//        $resource = fopen($path , 'a');
//        fwrite($resource, $file);
//        fclose($resource);


        $path = '../web/download/201711082216431.jpg';
        $base64_str = base64_encode(file_get_contents($path));

        $host = "https://dm-58.data.aliyun.com";
        $path = "/rest/160601/ocr/ocr_business_license.json";
        $method = "POST";
        $appcode = \Yii::$app->params['ali_print_app_code'];
        $headers = array();
        array_push($headers, "Authorization:APPCODE " . $appcode);
        //根据API的要求，定义相对应的Content-Type
        array_push($headers, "Content-Type" . ":" . "application/json; charset=UTF-8");
        $querys = "";
        $bodys = "{\"inputs\":[{\"image\":{\"dataType\":50,\"dataValue\":\"$base64_str\"}}]}";

        $url = $host . $path;
        $curl = curl_init();
        curl_setopt($curl, CURLOPT_CUSTOMREQUEST, $method);
        curl_setopt($curl, CURLOPT_URL, $url);
        curl_setopt($curl, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($curl, CURLOPT_FAILONERROR, false);
        curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($curl, CURLOPT_HEADER, false);
        if (1 == strpos("$" . $host, "https://")) {
            curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false);
            curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, false);
        }
        curl_setopt($curl, CURLOPT_POSTFIELDS, $bodys);
        $result = curl_exec($curl);
//        file_put_contents( '../web/download/test.txt',$result);

        $result = json_decode($result, true);
        if (isset($result['outputs'][0]['outputValue']['dataValue'])) {
            $dataValue = $result['outputs'][0]['outputValue']['dataValue'];
            $dataValue = json_decode($dataValue, true);
            var_dump($dataValue);
        }
    }
}
